from PySide6.QtWidgets import (QFrame, QTextEdit, QPushButton, 
                               QVBoxLayout, QHBoxLayout)
from PySide6.QtCore import Qt
import json
import sqlite3
import os
from PIL import Image

class PetAddWidget(QFrame):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.db = self.parent().db
        self.setObjectName("pet_add_window")
        self.setup_ui()
    
    def setup_ui(self):
        # 主垂直布局
        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.setContentsMargins(10, 10, 10, 10)
        
        # 文本编辑区域
        self.textEdit = QTextEdit(self)
        self.textEdit.setPlaceholderText("请输入内容...")
        self.textEdit.setMinimumHeight(150)
        self.mainLayout.addWidget(self.textEdit, 1)  # 1表示垂直方向可扩展
        
        # 按钮的水平布局
        self.buttonLayout = QHBoxLayout()
        
        # 清空按钮
        self.clearButton = QPushButton("清空", self)
        self.clearButton.clicked.connect(self.clear_text)
        self.clearButton.setMinimumSize(100, 60)
        self.buttonLayout.addWidget(self.clearButton)
        
        # 占位弹簧
        self.buttonLayout.addStretch(1)
        
        # 提交按钮
        self.submitButton = QPushButton("提交", self)
        self.submitButton.setMinimumSize(100, 60)
        self.submitButton.clicked.connect(self.handle_submit)
        self.buttonLayout.addWidget(self.submitButton)
        
        # 将按钮布局添加到主布局
        self.mainLayout.addLayout(self.buttonLayout)
        
    def clear_text(self):
        """清空文本内容"""
        self.textEdit.clear()
    
    def handle_submit(self):
        """处理提交操作"""
        content = self.textEdit.toPlainText()
        try:
            data = json.loads(content)
            self.db.insert_pet_data(data)
            self.clear_text()
            self.cut_img()
        except json.JSONDecodeError as e:
            self._show_error("JSON解析错误", str(e))
        except sqlite3.Error as e:
            self._show_error("数据库错误", str(e))
        except Exception as e:
            self._show_error("系统错误", str(e))
    
    def cut_img(self):
        # 用户配置区域
        input_folder = './long_screenshots'       # 输入文件夹路径
        output_folder = './pet_img'               # 输出文件夹路径
        default_image_path = './img/0.png'      # 备用图片路径
        x1, y1 = 18, 249                         # 左上角坐标
        x2, y2 = 318, 561                        # 右下角坐标

        # 预处理检查
        expected_width = x2 - x1
        expected_height = y2 - y1
        if x1 >= x2 or y1 >= y2:
            raise ValueError("坐标错误：x2必须大于x1，y2必须大于y1")

        if not os.path.exists(input_folder):
            raise FileNotFoundError(f"输入文件夹不存在: {input_folder}")

        if not os.path.exists(default_image_path):
            raise FileNotFoundError(f"备用图片不存在: {default_image_path}")

        os.makedirs(output_folder, exist_ok=True)

        # 预加载备用图片
        default_image = Image.open(default_image_path)
        if default_image.size != (expected_width, expected_height):
            print(f"警告：备用图片尺寸已自动调整为{expected_width}x{expected_height}")
            default_image = default_image.resize((expected_width, expected_height))

        supported_formats = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp')

        for filename in os.listdir(input_folder):
            if not filename.lower().endswith(supported_formats):
                continue

            output_path = os.path.join(output_folder, filename)
            
            # 跳过已存在的文件
            if os.path.exists(output_path):
                print(f"▏已存在：{filename}")
                continue

            input_path = os.path.join(input_folder, filename)
            
            try:
                with Image.open(input_path) as img:
                    w, h = img.size
                    
                    # 坐标有效性检查
                    if x1 < 0 or y1 < 0 or x2 > w or y2 > h:
                        print(f"▏警告：{filename} 超出原图尺寸({w}x{h})")
                        x1_adj = max(x1, 0)
                        y1_adj = max(y1, 0)
                        x2_adj = min(x2, w)
                        y2_adj = min(y2, h)
                    else:
                        x1_adj, y1_adj, x2_adj, y2_adj = x1, y1, x2, y2

                    # 计算实际裁剪尺寸
                    actual_width = x2_adj - x1_adj
                    actual_height = y2_adj - y1_adj
                    
                    # 判断是否需要使用备用图片
                    if actual_width < expected_width or actual_height < expected_height:
                        print(f"▏尺寸不足：{filename} 使用备用图片")
                        cropped = default_image.copy()
                    else:
                        # 执行正常裁剪
                        cropped = img.crop((x1_adj, y1_adj, x2_adj, y2_adj))
                        print(f"▏正常裁剪：{filename}")

                    # 格式兼容处理
                    if filename.lower().endswith(('.jpg', '.jpeg')):
                        if cropped.mode in ('RGBA', 'P'):
                            cropped = cropped.convert('RGB')
                    
                    cropped.save(output_path)

            except Exception as e:
                print(f"▏处理失败：{filename} | 错误：{str(e)}")
                # 保存备用图片作为兜底
                default_image.copy().save(output_path)
                print(f"▏已用备用图片兜底：{filename}")

        print("处理完成！缺失文件已用备用图片补全")